import { _decorator, Component, Label, Node, Sprite } from 'cc';
import { UIManager } from '../common/UIManager';
import { PrefabEnum } from '../common/PrefabEnum';
import { Tech } from '../entity/Tech';
import { Events } from '../entity/Events';
import { UserInfo } from '../common/UserInfo';
import { Utils } from '../common/Utils';
import { EventOper } from '../entity/Buildings';
import VillageApi from '../api/VillageApi';
const { ccclass, property } = _decorator;

@ccclass('UpgradingBuilding')
export class UpgradingBuilding extends Component {
    @property(Node)
    bg:Node
    @property(Node)
    close:Node
    @property(Label)
    title:Label
    @property(Sprite)
    cover:Sprite
    @property(Label)
    buildName:Label
    @property(Label)
    level:Label
    @property(Label)
    time:Label
    @property(Node)
    upgrade:Node

    techData:Tech
    offTime:number = 0

    start() {
        this.close.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.bg.on(Node.EventType.TOUCH_END, this.onClose, this)
        this.upgrade.on(Node.EventType.TOUCH_END, this.onSpeed, this)
    }

    async setData(tech:Tech){
        this.techData = tech
        this.title.string = tech.name + '强化'
        this.buildName.string = tech.name
        this.level.string = '当前等级' + tech.level

        this.cover.spriteFrame = await tech.getTechImg()

        let event = tech.getStudyEvent()
        if (event) {
            this.countDown(event)
        }
    }

    countDown(event: Events) {
        this.unschedule(this.updateTime)
        if (!event) {
            return
        }

        let eStartTime = event.eStartTime
        this.offTime = eStartTime - Math.floor(UserInfo.instance.serverTime / 1000)
        if (this.offTime <= 0) {
            this.onClose()
            return
        }

        this.time.string = `剩余时间：${Utils.secondToStr(this.offTime)}`
        this.schedule(this.updateTime, 1, this.offTime - 1)
    }

    updateTime() {
        this.offTime--
        this.time.string = `剩余时间：${Utils.secondToStr(this.offTime)}`

        if (this.offTime <= 0) {
            // 倒计时完成
            // 清除事件，刷新页面
           
            UserInfo.instance.refreshVillageDetail()
            this.onClose()
        }
    }

    onClose(){
        UIManager.instance.closeUI(PrefabEnum.UpgradingBuilding)
    }

    async onSpeed(){
        
        let event = this.techData.getStudyEvent()
        if(event) {
            let param = {
                ac: EventOper.SPEED_BUILD,
                eid: event.eHandle
            }
    
            await UIManager.instance.showLoading()
            let res = await VillageApi.eventOper(param)
            UIManager.instance.closeLoading()
            console.log(`加速升级，ac =${param.ac} ,del =${param.eid} `, res)
    
            await UserInfo.instance.refreshVillageDetail()
           
            
        } 

        this.onClose()
    }
}


